package com.atguigu.bigdata.chapter05.sink;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaProducer;
import org.apache.flink.streaming.connectors.kafka.KafkaSerializationSchema;
import org.apache.flink.util.Collector;
import org.apache.kafka.clients.producer.ProducerRecord;

import javax.annotation.Nullable;
import java.nio.charset.StandardCharsets;
import java.util.Properties;

import static org.apache.flink.streaming.connectors.kafka.FlinkKafkaProducer.Semantic.AT_LEAST_ONCE;

/**
 * @Author lzc
 * @Date 2022/9/2 9:04
 */
public class Flink02_Sink_Kafka_1 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        // 如果没有设置并行度, 并行度的值是cpu的核心数据
        Properties props = new Properties();
        props.setProperty("bootstrap.servers", "hadoop162:9092");
        env
            .readTextFile("input/words.txt")
            .flatMap(new FlatMapFunction<String, Tuple2<String, Long>>() {
                @Override
                public void flatMap(String value, Collector<Tuple2<String, Long>> out) throws Exception {
                    for (String word : value.split(" ")) {
                        out.collect(Tuple2.of(word, 1L));
                    }
                }
            })
            .keyBy(t -> t.f0)
            .sum(1)
            // 如果流中的数据不是字符串类型, 则需要自己定义序列化器
            .addSink(new FlinkKafkaProducer<Tuple2<String, Long>>(
                "defalut", // 这个topic没用
                new KafkaSerializationSchema<Tuple2<String, Long>>() {
                    @Override
                    public ProducerRecord<byte[], byte[]> serialize(Tuple2<String, Long> element,
                                                                    @Nullable Long timestamp) {
                        String msg = element.f0 + "_" + element.f1;
                        return new ProducerRecord<>("s1", msg.getBytes(StandardCharsets.UTF_8));
                    }
                },
                props,
                AT_LEAST_ONCE  // 写出的一致性语义: 目前只能选至少一次
            ));
        
        
        env.execute();
    }
}
